const { warn } = require("../utils/log_tool");
const { format, toArray } = require("../utils/transform_tool");
const { BaseCommand } = require("./base");

class EditExcelCommand extends BaseCommand {
    async execute() {
        const _Excel = require("exceljs");
        /**
         * @type {Excel.Workbook}
         */
        const workbook = this.content;
        /**
         * @type { {type: string, data: any}[] }
         */
        const actions = this.selfData.actions;
        actions.forEach((action) => {
            const data = action.data;
            switch (action.type) {
                case "insert_row": {
                    const sheet = workbook.getWorksheet(data.sheet ?? 1);
                    let row = data.row ?? 0;
                    if (row < 1) {
                        row = sheet.rowCount + 1 + row;
                    }
                    sheet.insertRow(row, data.value);
                    break;
                }
                case "modify": {
                    const sheet = workbook.getWorksheet(data.sheet ?? 1);
                    const cell = sheet.getCell(data.cell);
                    if (cell) {
                        cell.value = data.value;
                    }
                    break;
                }
                default: {
                    warn(`未支持的 edit_excel 类型 ${action.type}`);
                    break;
                }
            }
        });
    }

    getRequireContent() {
        return true;
    }

    getRequiredParams() {
        return ["actions"];
    }
}

module.exports = {
    EditExcelCommand,
};
